package com.volunteer.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.volunteer.common.R;
import com.volunteer.entity.Menu;
import com.volunteer.entity.RoleMenu;
import com.volunteer.service.MenuService;
import com.volunteer.service.RoleMenuService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/admin/menu")
@AllArgsConstructor
public class AdminMenuController {
    private final MenuService menuService;
    private final RoleMenuService roleMenuService;

    // 获取所有菜单
    @GetMapping("/list")
    public R<List<Menu>> list() {
        List<Menu> list = menuService.list(new LambdaQueryWrapper<Menu>().orderByAsc(Menu::getSort));
        return R.ok(list);
    }

    // 新增菜单
    @PostMapping("/add")
    public R<String> add(@RequestBody Menu menu) {
        boolean success = menuService.save(menu);
        return success ? R.ok("新增成功") : R.fail("新增失败");
    }

    // 更新菜单
    @PostMapping("/update")
    public R<String> update(@RequestBody Menu menu) {
        boolean success = menuService.updateById(menu);
        return success ? R.ok("更新成功") : R.fail("更新失败");
    }

    // 删除菜单
    @DeleteMapping("/delete/{id}")
    public R<String> delete(@PathVariable Long id) {
        boolean success = menuService.removeById(id);
        return success ? R.ok("删除成功") : R.fail("删除失败");
    }

    // 为角色分配菜单
    @PostMapping("/assign")
    public R<String> assignMenuToRole(@RequestParam Long roleId, @RequestBody List<Long> menuIds) {
        // 先删除原有
        roleMenuService.remove(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId, roleId));
        // 批量插入
        List<RoleMenu> list = menuIds.stream().map(menuId -> {
            RoleMenu rm = new RoleMenu();
            rm.setRoleId(roleId);
            rm.setMenuId(menuId);
            return rm;
        }).toList();
        boolean success = roleMenuService.saveBatch(list);
        return success ? R.ok("分配成功") : R.fail("分配失败");
    }

    // 获取角色的菜单id列表
    @GetMapping("/roleMenuIds")
    public R<List<Long>> getRoleMenuIds(@RequestParam Long roleId) {
        List<Long> ids = roleMenuService.list(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId, roleId))
                .stream().map(RoleMenu::getMenuId).toList();
        return R.ok(ids);
    }
} 